<?php
/**********
 * 发送邮件 *
 **********/
function SendMail($address,$title,$message)
{
    vendor('PHPMailer.class#phpmailer');

    $mail=new PHPMailer();
    // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();
    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet='UTF-8';	
	$mail->Encoding = "base64"; 	
	$mail->IsHTML(true);  // send as HTML
    // 添加收件人地址，可以多次使用来添加多个收件人
    if(is_array($address))
	{
		foreach($address as $k=>$v)
		{
			$mail->AddAddress($k);
		}
	}
	else
	{	
		$mail->AddAddress($address);
	}

    // 设置邮件正文
    $mail->Body="<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>".$message."<br><br>此邮件为系统自动发送。<br>".C('WEB_URL');
    // 设置邮件头的From字段。
    $mail->From=C('MAIL_USER');
    // 设置发件人名字
    $mail->FromName=C('WEB_TITLE');
    // 设置邮件标题
    $mail->Subject=$title;
    // 设置SMTP服务器。
    $mail->Host=C('MAIL_SMTP');
    // 设置为"需要验证"
    $mail->SMTPAuth=true;
    // 设置用户名和密码。
    $mail->Username=C('MAIL_USER');
    $mail->Password=C('MAIL_PASSWORD');
    // 发送邮件。
    return($mail->Send());
}

//生成新的凭证号码
function vouno_create($fadate)
{
	//$newvouno = M("Voumas")->where("PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'),'".date('Ym',$fadate)."') = 0")->getField("max(vouno)+1");
    $newvouno = M("Voumas")->where("vouno like '".date('Ym',$fadate)."%'")->getField("max(vouno)+1");
	$newvouno = $newvouno==null?date('Ym',$fadate).'0001':$newvouno;
	return $newvouno;
}
//生成新的SP号码
function sp_masno_create($mas_code,$fadate)
{
	//$newno = M("Spmas")->where("mas_code = '$mas_code' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'),'".date('Ym',$fadate)."') = 0")->getField("max(mas_no)+1");
    $newno = M("Spmas")->where("mas_code = '$mas_code' and mas_no like '".date('Ym',$fadate)."%'")->getField("max(mas_no)+1");
	$newno = $newno==null?date('Ym',$fadate).'0001':$newno;
	return $newno;
}
//生成新的STKIO号码
function stkio_masno_create($mas_code,$fadate)
{
	//$newno = M("Stkiomas")->where("mas_code = '$mas_code' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'),'".date('Ym',$fadate)."') = 0")->getField("max(mas_no)+1");
    $newno = M("Stkiomas")->where("mas_code = '$mas_code' and mas_no like '".date('Ym',$fadate)."%'")->getField("max(mas_no)+1");
	$newno = $newno==null?date('Ym',$fadate).'0001':$newno;
	return $newno;
}
//生成新的FACHECK号码
function facheck_masno_create($mas_code,$fadate)
{
	//$newno = M("Facheckmas")->where("mas_code = '$mas_code' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'),'".date('Ym',$fadate)."') = 0")->getField("max(mas_no)+1");
	$newno = M("Facheckmas")->where("mas_code = '$mas_code' and mas_no like '".date('Ym',$fadate)."%'")->getField("max(mas_no)+1");
	$newno = $newno==null?date('Ym',$fadate).'0001':$newno;
	return $newno;
}
//获取单据状态的名称
function get_status_title($status_flg,$color_diy=false)
{
	$status_title = $status_flg;
	switch($status_flg)
	{
		case 'A':
			$status_title = '活动中';
			if($color_diy){$status_title = '<font color="#0000FF">活动中</font>';}
			break;
		
		case 'C':
			$status_title = '已取消';
			if($color_diy){$status_title = '<font color="#AAAAAA">已取消</font>';}
			break;
		
		case 'P':
			$status_title = '已过账';
			if($color_diy){$status_title = '<font color="#AA0000">已过账</font>';}
			break;
		
		case 'E':
			$status_title = '有错误';
			break;
		
		case 'N':
			$status_title = '已存档';
			break;
		
	}
	return $status_title;
}
//获取单据的名称
function get_model_title($model_code,$color_diy=false)
{
	$model_title = $model_code;
	switch($model_code)
	{
		case 'SO':
			$model_title = '销售单';
			if($color_diy){$model_title = '<font color="#0000AA">销售单</font>';}
			break;		
		case 'RNC':
			$model_title = '销售退货单';
			if($color_diy){$model_title = '<font color="#AA0000">销售退货单</font>';}
			break;		
		case 'PO':
			$model_title = '采购单';
			if($color_diy){$model_title = '<font color="#0000AA">采购单</font>';}
			break;		
		case 'RNS':
			$model_title = '采购退货单';
			if($color_diy){$model_title = '<font color="#AA0000">采购退货单</font>';}
			break;		
		case 'VOUMAS':
			$model_title = '总账凭证';
			if($color_diy){$model_title = '<font color="#0000AA">总账凭证</font>';}
			break;
		case 'STKIN':
			$model_title = '其他入库单';
			if($color_diy){$model_title = '<font color="#222111">其他入库单</font>';}
			break;
		case 'STKOUT':
			$model_title = '其他出库单';
			if($color_diy){$model_title = '<font color="#222111">其他出库单</font>';}
			break;
		case 'WHSWITCH':
			$model_title = '仓库调拨单';
			if($color_diy){$model_title = '<font color="#222111">仓库调拨单</font>';}
			break;
		case 'ARCHKIN':
			$model_title = '收款';
			if($color_diy){$model_title = '<font color="#111222">收款</font>';}
			break;
		case 'APCHKOUT':
			$model_title = '付款';
			if($color_diy){$model_title = '<font color="#111222">付款</font>';}
			break;
		case 'SO-CHECK':
			$model_title = '销售出货收款';
			if($color_diy){$model_title = '<font color="#0000AA">销售出货收款</font>';}
			break;
		case 'RNC-CHECK':
			$model_title = '销售退货退款';
			if($color_diy){$model_title = '<font color="#AA0000">销售退货退款</font>';}
			break;
		case 'PO-CHECK':
			$model_title = '采购收货付款';
			if($color_diy){$model_title = '<font color="#0000AA">采购收货付款</font>';}
			break;
		case 'RNS-CHECK':
			$model_title = '采购退货退款';
			if($color_diy){$model_title = '<font color="#AA0000">采购退货退款</font>';}
			break;
		
		
		
	}
	return $model_title;
}
/* 保留小数位数
	$x 要四舍五入的数据
	$prec 要保留的小数位，默认是2位
	$show0 如果数据是0，显否要显示0，如果为FLASE，则显示为空

*/
function get_round($x,$prec=2,$show0=true)
{
	$r = round($x,$prec);
	if($r == 0 && $show0 == false)
	{
		$r = '';
	}
	return $r;
}
/* 检查会计期间状态
	$fadate 财务日期
	$lv 级别，0=无限制，1=仅财务单据，2=财务和仓存单据
	$ajax 如果true,则有输出，否则只有返回值

*/
function fiscalyp_check_common($fadate,$lv=2,$ajax=false)
{
		//var_dump((int)'2012-10-09');var_dump($fadate);var_dump(!is_int($fadate));exit;
		$model = M("Fiscalyp");
		if((int)$fadate < 10000) $fadate=strtotime($fadate);
		$yyyy = date('Y',$fadate);
		$mm = date('m',$fadate);
		$status_flg = $model -> where('f_year='.$yyyy.' and f_period='.$mm) -> getField('status_flg');
		if((int)$status_flg>=$lv)
		{
			if($ajax){echo 'true';}
			return true;
		}
		else
		{
			if($ajax){echo 'false';}
			return false;
		}
}
/* 出库时，库存扣除 
	***必须在主调程式上开启事务，当本函数返回带错误的信息时，回滚事务***
	$detail 扣账明细
*/
function deduct_stk($detail)
{
	if(C('STK_BATCH_ON'))
	{
		
	//=====================================启用批次管理================================
	//var_dump($detail);exit;
    //需要出库的商品：计算库存是否足够
	$outinfo['flg'] = true;
	$model_stk = M('Stkdetail');
	foreach($detail as $dtl)
	{
		unset($array_arg);
        $array_arg = md5($dtl['stk_id'].'|'.$dtl['wh_id'].'|'.$dtl['batch_no'].'|'.$dtl['expiry_date'].'|'.$dtl['approval_no'].'|'.$dtl['spec'].'|'.$dtl['madein']);
        $checkout[$array_arg]['fadate']=$dtl['fadate'];
		$checkout[$array_arg]['refcode']=$dtl['refcode'];
		$checkout[$array_arg]['refid']=$dtl['refid'];
		$checkout[$array_arg]['stk_id']=$dtl['stk_id'];
		$checkout[$array_arg]['wh_id']=$dtl['wh_id'];
        
        $checkout[$array_arg]['batch_no']=$dtl['batch_no'];
		$checkout[$array_arg]['expiry_date']=$dtl['expiry_date'];
		$checkout[$array_arg]['approval_no']=$dtl['approval_no'];
		$checkout[$array_arg]['spec']=$dtl['spec'];
		$checkout[$array_arg]['madein']=$dtl['madein'];
        
		$checkout[$array_arg]['cr_qty']+=(double)$dtl['cr_qty'];
	}
	//var_dump($checkout);exit;
	foreach($checkout as $dtl_row)
	{
		$hand_qty = (double)$model_stk->where("stk_id=".$dtl_row["stk_id"]." and wh_id=".$dtl_row["wh_id"]." and fadate<=".$dtl_row["fadate"]." and batch_no='".$dtl_row["batch_no"]."' and expiry_date='".$dtl_row["expiry_date"]."' and approval_no='".$dtl_row["approval_no"]."' and spec='".$dtl_row["spec"]."' and madein='".$dtl_row["madein"]."' ")->sum("open_qty");
		if($hand_qty<$dtl_row['cr_qty'])
		{
			$outinfo['flg'] = false;
			$outinfo['err'] = '001:qty';
			$outinfo['msg'] = '出库数量大于库存量';
			unset($outinfo['dtl']);
            unset($array_arg);
            $array_arg = md5($dtl_row['stk_id'].'|'.$dtl_row['wh_id'].'|'.$dtl['batch_no'].'|'.$dtl['expiry_date'].'|'.$dtl['approval_no'].'|'.$dtl['spec'].'|'.$dtl['madein']);
			$outinfo['dtl'][$array_arg]['stk_id'] = $dtl_row['stk_id'];
			$outinfo['dtl'][$array_arg]['wh_id'] = $dtl_row['wh_id'];
			$outinfo['dtl'][$array_arg]['cr_qty'] = $dtl_row['cr_qty'];
			$outinfo['dtl'][$array_arg]['hand_qty'] = $hand_qty;
		}
	}
	if($outinfo['flg']===false)
	{
		return $outinfo;exit;
	}		
	
	switch(C('COST_METHOD'))
	{
		case 'MAVG':
		case 'AVG':
			
			break;
		case 'LIFO':
			
			break;
		default: //FIFO
			//扣库存
			//var_dump($checkout);
			$amount_stk = 0;
			unset($outinfo['dtl']);
			foreach($checkout as $dtl_row)
			{
				$deduct_qty = $dtl_row['cr_qty']; //需扣减数量
				if($outdated_id) unset($outdated_id);
				$outdated_id[0]=0; //已扣减过的库存条目
				while($deduct_qty>0)
				{
					$rs = $model_stk->where("id not in (".implode(",",$outdated_id).") and stk_id=".$dtl_row["stk_id"]." and wh_id=".$dtl_row["wh_id"]." and fadate<=".$dtl_row["fadate"]." and open_qty>0 and batch_no='".$dtl_row["batch_no"]."' and expiry_date='".$dtl_row["expiry_date"]."' and approval_no='".$dtl_row["approval_no"]."' and spec='".$dtl_row["spec"]."' and madein='".$dtl_row["madein"]."' ")->order("fadate asc")->find();
					if($rs)
					{
						$rand_tmp = rand(100,999);
						if($deduct_qty >= $rs['open_qty'])
						{
							//全扣
							$upd_flg['id']=$rs['id'];
							$upd_flg['open_qty']=0;
							$upd_flg['open_amount']=0;
							
							$dtl_row['dr_qty']=0;
							$dtl_row['dr_amount']=0;
							$dtl_row['cr_qty']=$rs['open_qty'];
							$dtl_row['cr_amount']=$rs['open_amount'];
							$dtl_row['open_qty']=0;
							$dtl_row['open_amount']=0;
							$dtl_row['detail_id']=$rs['id'];
							
							$deduct_qty -= (double)$rs['open_qty'];
							$outdated_id[$rs['id']]=$rs['id'];
							
							$amount_stk += (double)$rs['open_amount'];
							
							//记录被扣的库存数据，以备使用（比如：在库存调拨单时...）
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['detail_id'] = $rs['id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['fadate'] = $rs['fadate'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['stk_id'] = $rs['stk_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['wh_id'] = $rs['wh_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['qty'] = $rs['open_qty'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['amount'] = $rs['open_amount'];
                            
                            $outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['batch_no'] = $rs['batch_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['expiry_date'] = $rs['expiry_date'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['approval_no'] = $rs['approval_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['spec'] = $rs['spec'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['madein'] = $rs['madein'];
						}
						else
						{
							//部分扣除
							$unit_cost = $rs['open_amount'] / $rs['open_qty'];
							$upd_flg['id']=$rs['id'];
							$upd_flg['open_qty']=$rs['open_qty'] - $deduct_qty;
							$upd_flg['open_amount']=($rs['open_qty'] - $deduct_qty)*$unit_cost;
							
							$dtl_row['dr_qty']=0;
							$dtl_row['dr_amount']=0;
							$dtl_row['cr_qty']=$deduct_qty;
							$dtl_row['cr_amount']=$deduct_qty*$unit_cost;
							$dtl_row['open_qty']=0;
							$dtl_row['open_amount']=0;
							$dtl_row['detail_id']=$rs['id'];
							
							$deduct_qty = 0;
							
							$amount_stk += (double)$dtl_row['cr_amount'];
							
							//记录被扣的库存数据，以备使用（比如：在库存调拨单时...）
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['detail_id'] = $rs['id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['fadate'] = $rs['fadate'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['stk_id'] = $rs['stk_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['wh_id'] = $rs['wh_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['qty'] = $dtl_row['cr_qty'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['amount'] = $dtl_row['cr_amount'];
                            
                            $outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['batch_no'] = $rs['batch_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['expiry_date'] = $rs['expiry_date'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['approval_no'] = $rs['approval_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['spec'] = $rs['spec'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['madein'] = $rs['madein'];
						}
						//var_dump($upd_flg);
						//var_dump($dtl_row);
						
						$row_result1 = $model_stk->data($upd_flg)->save();
						$row_result2 = $model_stk->add($dtl_row);
						if($row_result1 && $row_result2)
						{
							//todo							
						}
						else
						{
							$outinfo['flg'] = false;
							$outinfo['err'] = '003:writedb';
							$outinfo['msg'] = '写入数据时发生错误';
							unset($outinfo['dtl']);
							unset($array_arg);
                            $array_arg = md5($dtl_row['stk_id'].'|'.$dtl_row['wh_id'].'|'.$dtl['batch_no'].'|'.$dtl['expiry_date'].'|'.$dtl['approval_no'].'|'.$dtl['spec'].'|'.$dtl['madein']);
			
                            $outinfo['dtl'][$array_arg]['stk_id'] = $dtl_row['stk_id'];
							$outinfo['dtl'][$array_arg]['wh_id'] = $dtl_row['wh_id'];
							$outinfo['dtl'][$array_arg]['cr_qty'] = $dtl_row['cr_qty'];
							$outinfo['dtl'][$array_arg]['hand_qty'] = $dtl_row['cr_qty'] - $deduct_qty;
							return $outinfo;exit;
						}
					}
					else
					{
						$outinfo['flg'] = false;
						$outinfo['err'] = '002:qty';
						$outinfo['msg'] = '库存不足';
						unset($outinfo['dtl']);
                        unset($array_arg);
                        $array_arg = md5($dtl_row['stk_id'].'|'.$dtl_row['wh_id'].'|'.$dtl['batch_no'].'|'.$dtl['expiry_date'].'|'.$dtl['approval_no'].'|'.$dtl['spec'].'|'.$dtl['madein']);
			
						$outinfo['dtl'][$array_arg]['stk_id'] = $dtl_row['stk_id'];
						$outinfo['dtl'][$array_arg]['wh_id'] = $dtl_row['wh_id'];
						$outinfo['dtl'][$array_arg]['cr_qty'] = $dtl_row['cr_qty'];
						$outinfo['dtl'][$array_arg]['hand_qty'] = $dtl_row['cr_qty'] - $deduct_qty;
						return $outinfo;exit;
					}
				}
			}
			$outinfo['flg'] = true;
			$outinfo['err'] = '';
			$outinfo['msg'] = '操作已完成';
			$outinfo['amount_stk'] = $amount_stk;
			
			break;
	}
	return $outinfo;
	
	}
	else
	{
	
	//=====================================未启用批次管理================================
	//var_dump($detail);exit;
    //需要出库的商品：计算库存是否足够
	$outinfo['flg'] = true;
	$model_stk = M('Stkdetail');
	foreach($detail as $dtl)
	{
		unset($array_arg);
        $array_arg = md5($dtl['stk_id'].'|'.$dtl['wh_id']);
        $checkout[$array_arg]['fadate']=$dtl['fadate'];
		$checkout[$array_arg]['refcode']=$dtl['refcode'];
		$checkout[$array_arg]['refid']=$dtl['refid'];
		$checkout[$array_arg]['stk_id']=$dtl['stk_id'];
		$checkout[$array_arg]['wh_id']=$dtl['wh_id'];
        
        $checkout[$array_arg]['batch_no']=$dtl['batch_no'];
		$checkout[$array_arg]['expiry_date']=$dtl['expiry_date'];
		$checkout[$array_arg]['approval_no']=$dtl['approval_no'];
		$checkout[$array_arg]['spec']=$dtl['spec'];
		$checkout[$array_arg]['madein']=$dtl['madein'];
        
		$checkout[$array_arg]['cr_qty']+=(double)$dtl['cr_qty'];
	}
	//var_dump($checkout);exit;
	foreach($checkout as $dtl_row)
	{
		$hand_qty = (double)$model_stk->where("stk_id=".$dtl_row["stk_id"]." and wh_id=".$dtl_row["wh_id"]." and fadate<=".$dtl_row["fadate"]." ")->sum("open_qty");
		if($hand_qty<$dtl_row['cr_qty'])
		{
			$outinfo['flg'] = false;
			$outinfo['err'] = '001:qty';
			$outinfo['msg'] = '出库数量大于库存量-STK-ID:'.$dtl_row["stk_id"].'（'.M('Stkmas')->where(array('id'=>(int)$dtl_row["stk_id"]))->getField('title').'）';
			unset($outinfo['dtl']);
            unset($array_arg);
            $array_arg = md5($dtl_row['stk_id'].'|'.$dtl_row['wh_id']);
			$outinfo['dtl'][$array_arg]['stk_id'] = $dtl_row['stk_id'];
			$outinfo['dtl'][$array_arg]['wh_id'] = $dtl_row['wh_id'];
			$outinfo['dtl'][$array_arg]['cr_qty'] = $dtl_row['cr_qty'];
			$outinfo['dtl'][$array_arg]['hand_qty'] = $hand_qty;
		}
	}
	if($outinfo['flg']===false)
	{
		return $outinfo;exit;
	}		
	
	switch(C('COST_METHOD'))
	{
		case 'MAVG':
		case 'AVG':
			
			break;
		case 'LIFO':
			
			break;
		default: //FIFO
			//扣库存
			//var_dump($checkout);
			$amount_stk = 0;
			unset($outinfo['dtl']);
			foreach($checkout as $dtl_row)
			{
				$deduct_qty = $dtl_row['cr_qty']; //需扣减数量
				if($outdated_id) unset($outdated_id);
				$outdated_id[0]=0; //已扣减过的库存条目
				while($deduct_qty>0)
				{
					$rs = $model_stk->where("id not in (".implode(",",$outdated_id).") and stk_id=".$dtl_row["stk_id"]." and wh_id=".$dtl_row["wh_id"]." and fadate<=".$dtl_row["fadate"]." and open_qty>0 ")->order("fadate asc")->find();
					if($rs)
					{
						$rand_tmp = rand(100,999);
						if($deduct_qty >= $rs['open_qty'])
						{
							//全扣
							$upd_flg['id']=$rs['id'];
							$upd_flg['open_qty']=0;
							$upd_flg['open_amount']=0;
							
							$dtl_row['dr_qty']=0;
							$dtl_row['dr_amount']=0;
							$dtl_row['cr_qty']=$rs['open_qty'];
							$dtl_row['cr_amount']=$rs['open_amount'];
							$dtl_row['open_qty']=0;
							$dtl_row['open_amount']=0;
							$dtl_row['detail_id']=$rs['id'];
							
							$deduct_qty -= (double)$rs['open_qty'];
							$outdated_id[$rs['id']]=$rs['id'];
							
							$amount_stk += (double)$rs['open_amount'];
							
							//记录被扣的库存数据，以备使用（比如：在库存调拨单时...）
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['detail_id'] = $rs['id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['fadate'] = $rs['fadate'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['stk_id'] = $rs['stk_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['wh_id'] = $rs['wh_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['qty'] = $rs['open_qty'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['amount'] = $rs['open_amount'];
                            
                            $outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['batch_no'] = $rs['batch_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['expiry_date'] = $rs['expiry_date'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['approval_no'] = $rs['approval_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['spec'] = $rs['spec'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['madein'] = $rs['madein'];
						}
						else
						{
							//部分扣除
							$unit_cost = $rs['open_amount'] / $rs['open_qty'];
							$upd_flg['id']=$rs['id'];
							$upd_flg['open_qty']=$rs['open_qty'] - $deduct_qty;
							$upd_flg['open_amount']=($rs['open_qty'] - $deduct_qty)*$unit_cost;
							
							$dtl_row['dr_qty']=0;
							$dtl_row['dr_amount']=0;
							$dtl_row['cr_qty']=$deduct_qty;
							$dtl_row['cr_amount']=$deduct_qty*$unit_cost;
							$dtl_row['open_qty']=0;
							$dtl_row['open_amount']=0;
							$dtl_row['detail_id']=$rs['id'];
							
							$deduct_qty = 0;
							
							$amount_stk += (double)$dtl_row['cr_amount'];
							
							//记录被扣的库存数据，以备使用（比如：在库存调拨单时...）
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['detail_id'] = $rs['id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['fadate'] = $rs['fadate'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['stk_id'] = $rs['stk_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['wh_id'] = $rs['wh_id'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['qty'] = $dtl_row['cr_qty'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['amount'] = $dtl_row['cr_amount'];
                            
                            $outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['batch_no'] = $rs['batch_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['expiry_date'] = $rs['expiry_date'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['approval_no'] = $rs['approval_no'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['spec'] = $rs['spec'];
							$outinfo['dtl'][$rs['id'].'|'.$rand_tmp]['madein'] = $rs['madein'];
						}
						//var_dump($upd_flg);
						//var_dump($dtl_row);
						
						$row_result1 = $model_stk->data($upd_flg)->save();
						$row_result2 = $model_stk->add($dtl_row);
						if($row_result1 && $row_result2)
						{
							//todo							
						}
						else
						{
							$outinfo['flg'] = false;
							$outinfo['err'] = '003:writedb';
							$outinfo['msg'] = '写入数据时发生错误';
							unset($outinfo['dtl']);
							unset($array_arg);
                            $array_arg = md5($dtl_row['stk_id'].'|'.$dtl_row['wh_id']);
			
                            $outinfo['dtl'][$array_arg]['stk_id'] = $dtl_row['stk_id'];
							$outinfo['dtl'][$array_arg]['wh_id'] = $dtl_row['wh_id'];
							$outinfo['dtl'][$array_arg]['cr_qty'] = $dtl_row['cr_qty'];
							$outinfo['dtl'][$array_arg]['hand_qty'] = $dtl_row['cr_qty'] - $deduct_qty;
							return $outinfo;exit;
						}
					}
					else
					{
						$outinfo['flg'] = false;
						$outinfo['err'] = '002:qty';
						$outinfo['msg'] = '库存不足';
						unset($outinfo['dtl']);
                        unset($array_arg);
                        $array_arg = md5($dtl_row['stk_id'].'|'.$dtl_row['wh_id']);
			
						$outinfo['dtl'][$array_arg]['stk_id'] = $dtl_row['stk_id'];
						$outinfo['dtl'][$array_arg]['wh_id'] = $dtl_row['wh_id'];
						$outinfo['dtl'][$array_arg]['cr_qty'] = $dtl_row['cr_qty'];
						$outinfo['dtl'][$array_arg]['hand_qty'] = $dtl_row['cr_qty'] - $deduct_qty;
						return $outinfo;exit;
					}
				}
			}
			$outinfo['flg'] = true;
			$outinfo['err'] = '';
			$outinfo['msg'] = '操作已完成';
			$outinfo['amount_stk'] = $amount_stk;
			
			break;
	}
	return $outinfo;
	
	}
}

/* 收付款核销时，回写原总账的OPEN AMOUNT 
	***必须在主调程式上开启事务，当本函数返回带错误的信息时，回滚事务***
	$detail 扣账明细
*/
function deduct_gl($detail)
{
	$outinfo['flg'] = true;
	$model_vouitem = M('Vouitem');
	$ids = '0'; //vouitem id(s)
	foreach($detail as $dtl)
	{
		$checkout[$dtl['refid']]['refid']=$dtl['refid'];
		$checkout[$dtl['refid']]['curr_open_amount']=$dtl['curr_open_amount'];
		$checkout[$dtl['refid']]['open_amount']=$dtl['open_amount'];
		$ids .= ','.$dtl['refid'];
	}
	$deduct_data = $model_vouitem->where('id in ('.$ids.')')->select();
	foreach($deduct_data as $dtl_row)
	{
		if((double)$dtl_row['curr_open_amount']>=(double)$checkout[$dtl_row['id']]['curr_open_amount'])
		{
			$data['id']=$dtl_row['id'];
			$data['curr_open_amount']=(double)$dtl_row['curr_open_amount'] - (double)$checkout[$dtl_row['id']]['curr_open_amount'];
			$data['open_amount']=(double)$dtl_row['open_amount'] - (double)$checkout[$dtl_row['id']]['open_amount'];
			$model_vouitem->data($data)->save();
		}
		else
		{
			$outinfo['flg'] = false;
			$outinfo['err'] = '001:qty';
			$outinfo['msg'] = '余额不足：可能已被其他单据核销';
			$outinfo['dtl'][$dtl_row['id']]['refid'] = $dtl_row['id'];
			$outinfo['dtl'][$dtl_row['id']]['curr_open_amount'] = $dtl_row['curr_open_amount'];
			$outinfo['dtl'][$dtl_row['id']]['curr_writeoff_amount'] = $checkout[$dtl_row['id']]['curr_open_amount'];
			return $outinfo;exit;
		}
	}		
	
	return $outinfo;
}


/* 获取科目余额 
	$acc_code 科目代码
	$fadate 财务日期 int（YYYY-MM-DD用strtotime转换成的数字）
	$actflg = day | month	
	$todown 是否要把所有下级科目的余额全部算进来
*/
function get_acc_closing($acc_code,$fadate=0,$actflg='day',$outvalue=0,$todown=false)
{
	if(!$fadate) $fadate=time();
	if($actflg=='day')
	{
		$subQuery = M('Voumas')->field('id')->where("status_flg in ('P') and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m%d'),'".date('Ymd',$fadate)."') <= 0")->select(false);
	}else{
		$subQuery = M('Voumas')->field('id')->where("status_flg in ('P') and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'),'".date('Ym',$fadate)."') <= 0")->select(false);
	}
	
	
	$outvalue+=(double)M('Vouitem')->where('acc_code=\''.$acc_code.'\' and masid in '.$subQuery)->sum('dr-cr');
	
	
	$subQuery = M('Faccmas')->field('id')->where('code=\''.$acc_code.'\'')->select(false);
	$subAcc = $todown==true ? M('Faccmas')->field('id','code')->where('parentid in '.$subQuery)->select() : 0;
	if($subAcc)
	{
		foreach($subAcc as $row)
		{
			get_acc_closing($row['code'],$fadate,$actflg,$outvalue);
		}
	}else{
		$acc_diyinfo=unserialize(M('Faccmas')->where('code=\''.$acc_code.'\'')->getField('diyinfo'));
		//$acc_diyinfo['arctrl']=='Y' || $acc_diyinfo['apctrl']=='Y' || $acc_diyinfo['precollected']=='Y' || $acc_diyinfo['prepaid']=='Y'
		$acc_sign = $acc_diyinfo['credit']=='Y'? -1 : 1;
		return $outvalue*$acc_sign;
	}
	
}
/**
	验证系统授权
*/
function check_system()
{
    vendor('MisoneAction.misone#action');
	$mac = new GetMacAddr(PHP_OS);
	$reginfo = $mac->mac_addr;
	if(!$reginfo) $reginfo = rand(10000,99999);
	
	$model = M('Test');
	$chkinfo = $model->select();
	foreach($chkinfo as $row)
	{
		$check_info[$row['code']]['code']=$row['code'];
		$check_info[$row['code']]['html']=$row['html'];
		$check_info[$row['code']]['php']=$row['php'];
	}
	$vouminid=(int)M('Voumas')->getField('count(id)');
	if($vouminid>100)
	{
		//注册码
		if( $check_info[md5('check_system')]['html'] != md5($reginfo.md5(C('REGISTER_PASS')).md5(C('REGISTER_VER')))  )
		{
			echo '<script type="text/javascript">top.window.location.href="'.PHP_FILE . C ( 'SYS_REGISTER' ).'";</script>';
			exit;
		}
		//限制修改主要模板
		$checkfile = C('APP_PATH_DIY').'/web_config_diy.php';
		if( $check_info[md5('web_config')]['html'] != md5(md5_file($checkfile))  )
		{
			//echo '<script type="text/javascript">top.window.location.href="'.PHP_FILE . C ( 'SYS_BE_MODIFY' ).'";</script>';
			//exit;
		}
		$checkfile = C('APP_PATH_DIY').'/Erp/Tpl/Index/index.html';
		if( $check_info[md5('index')]['html'] != md5(md5_file($checkfile))  )
		{
			//echo '<script type="text/javascript">top.window.location.href="'.PHP_FILE . C ( 'SYS_BE_MODIFY' ).'";</script>';
			//exit;
		}
		$checkfile = C('APP_PATH_DIY').'/Erp/Tpl/Public/login.html';
		if( $check_info[md5('login')]['html'] != md5(md5_file($checkfile))  )
		{
			//echo '<script type="text/javascript">top.window.location.href="'.PHP_FILE . C ( 'SYS_BE_MODIFY' ).'";</script>';
			//exit;
		}
		
		$checkfile = C('APP_PATH_DIY').'/Erp/Tpl/Public/menubar.html';
		if( $check_info[md5('menubar')]['html'] != md5(md5_file($checkfile))  )
		{
			//echo '<script type="text/javascript">top.window.location.href="'.PHP_FILE . C ( 'SYS_BE_MODIFY' ).'";</script>';
			//exit;
		}
		
	}
	
}

function get_date($src_format,$src_date)
{
	$r = '';
    if($src_date)
	{
		$r = date($src_format,$src_date);
	}
	return $r;
}

function get_cny($data) {  
   $capnum=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖");  
   $capdigit=array("","拾","佰","仟");  
   $subdata=explode(".",$data);  
   $yuan=$subdata[0];  
   $j=0; $nonzero=0;  
   for($i=0;$i<strlen($subdata[0]);$i++) {  
      if(0==$i) { //确定个位  
         if(isset($subdata[1])) {  
            $cncap=(substr($subdata[0],-1,1)!=0)?"元":"元零";  
         }else{  
            $cncap="元";  
         }  
      }    
      if(4==$i) { $j=0; $nonzero=0; $cncap="万".$cncap; } //确定万位  
      if(8==$i) { $j=0; $nonzero=0; $cncap="亿".$cncap; } //确定亿位  
      $numb=substr($yuan,-1,1); //截取尾数  
      $cncap=($numb)?$capnum[$numb].$capdigit[$j].$cncap:(($nonzero)?"零".$cncap:$cncap);  
      $nonzero=($numb)?1:$nonzero;  
      $yuan=substr($yuan,0,strlen($yuan)-1); //截去尾数    
      $j++;  
   }  
  $chiao = $cent = "";  
  $zhen = "整";  
   if(isset($subdata[1])) {  
     $chiao=(substr($subdata[1],0,1))?$capnum[substr($subdata[1],0,1)]."角":"零";  
     $cent=(substr($subdata[1],1,1))?$capnum[substr($subdata[1],1,1)]."分":"零分";  
     $zhen="";  
   }  
 
   $cncap .= $chiao.$cent.$zhen;  
   $cncap=preg_replace("/(零)+/","\\1",$cncap); //合并连续“零”  
   return $cncap;  
}  

function check_disc($disc_rate){
    if((string)$disc_rate == '')
	{
		return '100';
	}
	else if( (int)$disc_rate<0 || (int)$disc_rate>100 )
	{
		return '100';
	}
	else
	{
		return $disc_rate;
	}
}

?>